package com.nali.dal.statement.upsert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.nali.dal.dao.general.IGeneralInsertDao;
import com.nali.dal.expression.PropertyExpression;
import com.nali.dal.expression.query.Criteria;
import com.nali.dal.statement.query.ColumnUnit;
import com.nali.dal.statement.query.ColumnUnitConfig;
import com.nali.dal.statement.query.ColumnUnitFactory;
import com.nali.dal.statement.util.DalCollectionUtils;

public class InserterImpl implements Inserter {
	@Autowired
	private ColumnUnitFactory columnUnitFactory;
	private IGeneralInsertDao insertDao;
	private String table;
	private List<ColumnUnitConfig> columnUnitList;

	public void setValues(List<String> columns) {
		columnUnitList = new ArrayList<ColumnUnitConfig>();
		for (String col : columns) {
			ColumnUnitConfig columnUnitConfig = columnUnitFactory.compile(col);
			for (PropertyExpression<Criteria> pc : columnUnitConfig.getColumnCriterias()) {
				if(pc.getExpression() != Criteria.select) {
					throw new IllegalArgumentException("not supported expression:" + col);
				}
			}
			columnUnitList.add(columnUnitConfig);
		}
	}

	@Override
	public int upsert(Map<String, Object> lineDatas) {
		Map<String,Object> datas = DalCollectionUtils.newHashMap(columnUnitList.size());
		for (ColumnUnitConfig cfg : columnUnitList) {
			ColumnUnit columnUnit = cfg.getColumnUnit();
			datas.put(columnUnit.getName(), columnUnit.getColumnValue(lineDatas));
		}
		insertDao.insert(table, datas);
		return 1;
	}

	public void setColumnUnitFactory(ColumnUnitFactory columnUnitFactory) {
		this.columnUnitFactory = columnUnitFactory;
	}

	public void setInsertDao(IGeneralInsertDao insertDao) {
		this.insertDao = insertDao;
	}

	public void setTable(String table) {
		this.table = table;
	}
}
